package com.rc.web.service.impl;

import com.google.common.collect.ImmutableMap;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rc.common.constant.Code;
import com.rc.common.constant.CollectType;
import com.rc.common.constant.OrderType;
import com.rc.common.exception.BusinessException;
import com.rc.common.util.RabbitMqHelper;
import com.rc.pojo.dto.activity.ActivityAddDTO;
import com.rc.pojo.dto.activity.ActivityPageQuery;
import com.rc.pojo.dto.activity.UpdateActivityDTO;
import com.rc.pojo.po.Activity;
import com.rc.pojo.po.Area;
import com.rc.pojo.vo.activity.ActivityDetailVO;
import com.rc.pojo.vo.activity.ActivityListVO;
import com.rc.pojo.vo.activity.ActivityVO;
import com.rc.pojo.vo.activity.PageActivityVO;
import com.rc.web.converter.ActivityConverter;
import com.rc.web.mapper.ActivityMapper;
import com.rc.web.service.ActivityService;
import com.rc.web.service.AreaService;
import com.rc.web.service.CollectService;
import com.rc.web.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 活动表 服务层实现。
 * 提供活动相关的业务逻辑实现
 */
@Service
@RequiredArgsConstructor(onConstructor_= {@Lazy})
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {
    // 活动转换器
    private final ActivityConverter activityConverter;
    // 收藏服务
    private final CollectService collectService;
    // 区域服务
    private final AreaService areaService;
    // 订单服务
    private final OrderService orderService;
    // RabbitMQ工具类
    private final RabbitMqHelper rabbitMqHelper;

    /**
     * 获取活动列表
     * @return 活动列表VO
     */
    @Override
    public List<ActivityListVO> getList() {
        var now = LocalDateTime.now();
        var activityList = this.list();

        return activityList.stream()
                .map(activity -> {
                    var vo = activityConverter.toListVO(activity);
                    var isEnd = vo.getEndTime().isBefore(now) || vo.getBeginTime().isAfter(now);
                    vo.setIsEnd(false);
                    return vo;
                })
                .sorted((o1, o2) -> {
                    var o1Seconds = Duration.between(o1.getBeginTime(), now).getSeconds();
                    var o2Seconds = Duration.between(o2.getBeginTime(), now).getSeconds();
                    return Long.compare(o1Seconds,o2Seconds);
                })
                .toList();
    }

    /**
     * 获取活动详情
     * @param id 活动ID
     * @return 活动详情VO
     */
    @Override
    public ActivityDetailVO detail(Long id) {
        var row =  mapper.selectDetail(id);

        if (row == null){
            throw new BusinessException(Code.NO_SUCH_ACTIVITY);
        }

        var vo = row.toEntity(ActivityDetailVO.class);

        //查询用户是否收藏
        var collect = collectService.isCollect(id, CollectType.ACTIVITY);
        vo.setIsCollect(collect);

        //查询该活动今天的销量
        var todaySold = orderService.getItemTodaySold(id, OrderType.ACTIVITY);

        //设置当前库存
        vo.setStock(vo.getStock() - todaySold);
        return vo;
    }

    /**
     * 添加活动
     * @param dto 活动添加DTO
     */
    @Override
    public void add(ActivityAddDTO dto) {
        var activity = activityConverter.addDTO2PO(dto);

        var area = areaService.getById(activity.getAreaId());

        //园区为null 或者 园区所属农场与当前用户农场id不一致
        if (area == null){
            throw new BusinessException(Code.NO_SUCH_AREA);
        }

        this.save(activity);
    }

    /**
     * 分页查询活动
     * @param dto 分页查询条件
     * @return 分页结果
     */
    @Override
    public Page<PageActivityVO> getPage(ActivityPageQuery dto) {
        return mapper.selectPage(dto);
    }

    /**
     * 根据ID删除活动
     * @param id 活动ID
     */
    @Override
    public void deleteOneById(Long id) {
        var success = this.removeById(id);

        if (!success){
            throw new BusinessException(Code.NO_SUCH_ACTIVITY);
        }
    }

    /**
     * 更新活动信息
     * @param dto 活动更新DTO
     */
    @Override
    public void updateOneById(UpdateActivityDTO dto) {
        var area = areaService.getById(dto.getAreaId());

        if (area == null){
            throw new BusinessException(Code.NO_SUCH_AREA);
        }

        var activity = activityConverter.updateDTO2PO(dto);
        activity.setBeginTime(dto.getBeginTime().atStartOfDay());
        activity.setEndTime(dto.getEndTime().atStartOfDay());

        var success= this.updateById(activity);
        if (!success){
            throw new BusinessException(Code.NO_SUCH_ACTIVITY);
        }

        var msg = ImmutableMap.<String,Object>builder()
                .put("itemId", activity.getId())
                .put("type", CollectType.ACTIVITY)
                .build();

        rabbitMqHelper.sendMessage("item.direct","update", msg);
    }

    /**
     * 根据ID获取活动信息
     * @param id 活动ID
     * @return 活动VO
     */
    @Override
    public ActivityVO getOneById(Long id) {
        var activity = this.getById(id);
        return activityConverter.toVO(activity);
    }
}
